import sys
import os
import time
import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter, MultipleLocator
from matplotlib.markers import MarkerStyle
from models.history import History

def majortickrepr(x, pos):
    # date from unix timestamp
    dat = datetime.datetime.fromtimestamp(x)
    if dat.day > 16:
        dat += datetime.timedelta(hours=360)
    month = dat.strftime('%B')[:3]
    return dat.strftime('%Y\n{0}\n%d'.format(month))

def getxaxisbeginning(x):
    first = datetime.datetime.fromtimestamp(x)
    first -= datetime.timedelta(days=first.day)

def main(argv):
    if len(argv) > 1:
        target = os.path.abspath(argv[1])
    else:
        target = os.path.dirname(os.path.realpath(argv[0]))

    # before operation, if directory doesn't exist

    # think of fitting datastructure for moddates and counts
    data = History()

    for root, dirs, files in os.walk(target):
        for f in files:
            fs = f.split('-')
            if "IMG" in fs[0]:
                #print(fs)
                moddate = time.mktime(datetime.datetime.strptime(fs[1], "%Y%m%d").timetuple())
                data.record(moddate)

    print("so far, success!")
    print(data)

    # data for graphic
    x = data.dates
    y = data.datescount

    # axis relevant code

    plt.axis([getxaxisbeginning(data.lowestdate()), data.highestdate(), data.lowestcount(), data.highestcount()])
    fig, ax = plt.subplots()
    ax.xaxis.set_major_formatter(FuncFormatter(majortickrepr))
    # 1 month in seconds
    ax.xaxis.set_major_locator(MultipleLocator(2592000))
    plt.minorticks_on()
    ax.xaxis.set_major_formatter(FuncFormatter(majortickrepr))

    # grid relevant code
    plt.grid(True)

    # plot finalization
    plt.scatter(x, y, s=8**2, marker=MarkerStyle(marker='x'), alpha=0.5)
    plt.show()


if __name__ == "__main__":
   main(sys.argv)
